import { cmdExport } from '@/commands/standard';
import { RenderBase } from '@/common/cmdBase/renderBase';
import { useDocumentStore } from '@/common/store';
import { ModelTreeObjectType } from '@/common/types';
import { basic } from '@/domain';
import { useEffect, useRef, useState } from 'react';
import { ILeftMenuItem } from '../..';
import { ContentMenu } from './ContentMenu';
import ModelTree from './ModelTree';

export const LeftLayout = () => {
  const { modelTreeInfo } = useDocumentStore();
  const renderBase = useRef(new RenderBase());
  const menuRef = useRef(null); // 右键菜单的 Ref
  // 设置右键的模型树数据，用于显示右键菜单并控制右键菜单的内容
  const [contextMenuData, setContextMenuData] = useState<ModelTreeObjectType[]>(
    [],
  );
  // 记录右键菜单需要显示的位置
  const [contextMenuPosition, setContextMenuPosition] = useState({
    x: 0,
    y: 0,
  }); // 记录右键弹窗所属的位置

  // 全局点击监听（点击空白处关闭菜单）
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (
        contextMenuData && // 菜单当前可见
        menuRef.current && // 菜单容器已挂载
        !menuRef.current.contains(e.target) // 点击的不是菜单内部
      ) {
        closeContextMenu();
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [contextMenuData]);

  // 关闭上下文菜单
  const closeContextMenu = () => {
    setContextMenuData([]);
  };
  // 处理右键点击
  const handleRowContextMenu = (
    event: MouseEvent,
    data: ModelTreeObjectType[],
  ) => {
    event.preventDefault();
    // 计算菜单位置
    const x = event.clientX;
    const y = event.clientY;
    setContextMenuPosition({ x, y });
    setContextMenuData(data);
  };
  const handleOnHover = (data: ModelTreeObjectType, hovered: boolean) => {
    if (data.shape) {
      // 当节点被悬停/移出时，同时hover/unhover模型
      renderBase.current.meshMgr?.setEntityHovered(hovered, data.shape);
      renderBase.current.render();
    }
  };
  /**
   * 过滤掉Folder，并返回dxid数组
   * @param data
   * @returns
   */
  const filterAndMapTreeObject = (data: ModelTreeObjectType[]) => {
    return data
      .filter((item) => item.type !== 'Folder')
      .map((item) => item.dxid);
  };
  const handleMenuClick = async (data: ModelTreeObjectType[], key: string) => {
    switch (key) {
      case 'show':
      case 'hide':
        {
          const objects = data.map((item) => item.dxid);
          const visible = key === 'show';
          await basic.setVisibility(objects, visible);
          // 操作成功之后，会后端会发送事件，在事件处理中，进行模型的显隐操作
        }
        break;
      case 'exportStep':
        {
          // 批量导出step；Folder不可导出，过滤掉
          const filteredObjects = filterAndMapTreeObject(data);
          await cmdExport('step', filteredObjects, data[0].label);
        }
        break;
      case 'exportObj':
        {
          // 批量导出obj；Folder不可导出，过滤掉
          const filteredObjects = filterAndMapTreeObject(data);
          await cmdExport('obj', filteredObjects, data[0].label);
        }
        break;
      case 'delete':
        {
          // Folder不可删除，过滤掉
          const filteredObjects = filterAndMapTreeObject(data);
          await basic.deleteObjects(filteredObjects);
        }
        break;
    }
    closeContextMenu();
  };
  return (
    <div
      style={{
        position: 'absolute',
        minWidth: 200,
        maxWidth: 400,
        margin: 6,
        overflow: 'auto',
        background: 'transparent',
        zIndex: 10,
        height: `calc(100vh - ${window.__MICRO_APP_ENVIRONMENT__ ? 282 : 211}px)`,
        pointerEvents: 'none',
      }}
      onContextMenu={(e) => {
        const target = e.target as HTMLElement;
        // 点击空白处关闭菜单
        if (target.tagName === 'DIV') {
          closeContextMenu();
        }
      }}>
      <ModelTree
        initialData={modelTreeInfo}
        onContextMenu={handleRowContextMenu}
        onHover={handleOnHover}
      />
      {/* 右键菜单 */}
      {contextMenuData.length > 0 && (
        <ContentMenu
          ref={menuRef}
          data={contextMenuData}
          onClick={handleMenuClick}
          position={contextMenuPosition}></ContentMenu>
      )}
    </div>
  );
};

export const Database: ILeftMenuItem = {
  id: 'database',
  label: '模型树',
  icon: 'commands/leftPanel/database',
  type: 'panel',
  boxWidth: 400,
  fixed: false,
  focus: true,
  describe: <div>模型树</div>,
  create: () => <LeftLayout />,
};
